<?php

namespace app\agent\model;

use think\facade\Db;

/**
 * 用户提现
 */
class UserWithdraw
{
    private $table = 'user_withdraw';





    /**
     * 列表
     */
    public function getList($params)
    {
        $where = [];
        $where[] = ['agent_id', '=', $params['agent_id']];
        if (!empty($params['status'])) {
            $where[] = ['status', '=', $params['status']];
        }
        $paginate = [
            'page' => $params['page'] ?? 1,
            'list_rows' => $params['list_rows'] ?? 10,
        ];
        $list = Db::name($this->table)
            ->where($where)
            ->order('id desc')
            ->paginate($paginate)
            ->toArray();
        if (empty($list['data'])) {
            return success('操作成功', $list);
        }

        $userIds = array_column($list['data'], 'user_id');
        $userList = Db::name('user')
            ->whereIn('id', $userIds)
            ->column('nickname, avatar, balance', 'id');
        foreach ($list['data'] as $k => $v) {
            $user = $userList[$v['user_id']];
            $list['data'][$k]['balance'] = $user['balance'];
            $list['data'][$k]['avatar'] = $user['avatar'];
            $list['data'][$k]['nickname'] = $user['nickname'];
        }

        return success('操作成功', $list);
    }

    /**
     * 提现审核通过
     */
    public function accept($params)
    {
        if (empty($params['id'])) {
            return fail('参数有误');
        }

        $info = Db::name($this->table)
            ->where('id', $params['id'])
            ->where('agent_id', $params['agent_id'])
            ->find();
        if (empty($info)) {
            return fail('提现申请不存在');
        }

        if ($info['status'] != 1) {
            return fail('该提现申请已经处理过');
        }

        $openid = Db::name('user')
            ->where('id', $info['user_id'])
            ->value('openid');

        $res = [];
        if ($info['type'] == 2) {
            // 企业付款到微信零钱
            // $pay = new \app\common\model\Wxpay($params['agent_id']);
            // $res = $pay->transferToBalance([
            //     'partner_trade_no' => 'user-' . $info['id'],
            //     'openid' => $openid,
            //     'amount' => $info['real_amount'],
            //     'desc' => '提现',
            // ]);
            // if (!isset($res['result_code']) || $res['result_code'] != 'SUCCESS') {
            //     return fail($res['err_code_des'] ?? '企业付款到微信零钱失败');
            // }
        }

        Db::startTrans();
        try {
            Db::name($this->table)
                ->where('id', $info['id'])
                ->update([
                    'status' => 2,
                ]);
            Db::name('user')
                ->where('id', $info['user_id'])
                ->inc('withdraw_amount', $info['amount'])
                ->update();

            Db::commit();
        } catch(\Exception $e) {
            Db::rollback();
            return fail('审核失败：' . $e->getMessage());
        }

        return success("审核成功", $res);
    }

    /**
     * 提现审核不通过
     */
    public function reject($params)
    {
        if (empty($params['id'])) {
            return fail('参数有误');
        }
        if (!empty($params['remark']) && mb_strlen($params['remark']) > 255) {
            return fail('驳回理由不能超过 255 个字符');
        }

        $info = Db::name($this->table)
            ->where('id', $params['id'])
            ->where('agent_id', $params['agent_id'])
            ->find();
        if (empty($info)) {
            return fail('提现申请不存在');
        }

        if ($info['status'] != 1) {
            return fail('该提现申请已经处理过');
        }

        $user = Db::name('user')
            ->field('balance')
            ->where('id', $info['user_id'])
            ->where('agent_id', $info['agent_id'])
            ->find();
        if (empty($user)) {
            return fail('用户不存在');
        }

        Db::startTrans();
        try {
            Db::name($this->table)
                ->where('id', $info['id'])
                ->update([
                    'status' => 3,
                    'remark' => $params['remark'] ?? '',
                ]);
            Db::name('user')
                ->where('id', $info['user_id'])
                ->inc('balance', $info['amount'])
                ->update();
            Db::name('user_balance_log')
                ->insert([
                    'agent_id' => $info['agent_id'],
                    'user_id' => $info['user_id'],
                    'amount' => $info['amount'],
                    'old_balance' => $user['balance'],
                    'new_balance' => $user['balance'] + $info['amount'],
                    'type' => 2,    // 1提现申请 2提现驳回
                    'quote_id' => $info['id'],
                ]);

            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
            return fail('审核失败：' . $e->getMessage());
        }

        return success('驳回成功');
    }
}
